package com.wx.app.card.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.app.card.config.WxMaConfiguration;
import com.wx.app.card.dao.entity.FriendEntity;
import com.wx.app.card.dao.entity.PVEntity;
import com.wx.app.card.dao.entity.UVEntity;
import com.wx.app.card.dao.entity.UserEntity;
import com.wx.app.card.dao.mapper.FriendMapper;
import com.wx.app.card.dao.mapper.PVMapper;
import com.wx.app.card.dao.mapper.UVMapper;
import com.wx.app.card.dao.mapper.UserMapper;
import com.wx.app.card.domain.ro.LoginRO;
import com.wx.app.card.domain.ro.UploadFriendRO;
import com.wx.app.card.domain.ro.UploadUserInfoRO;
import com.wx.app.card.domain.vo.LoginVO;
import com.wx.app.card.domain.vo.UserInfo;
import com.wx.app.card.utils.CacheUtils;
import com.wx.app.card.utils.IpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 类功能描述：
 *
 * @author：刘富国
 * @createTime：2019/7/30 19:43
 */
@Api(tags = "-登录模块")
@Slf4j
@RestController
public class LoginController extends BaseController {

    @Value("${wx.miniapp.default}")
    private String appid;
    private WxMaService wxService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private PVMapper pvMapper;
    @Autowired
    private UVMapper uvMapper;


    @PostConstruct
    private void initService() {
        wxService = WxMaConfiguration.getMaService(appid);
    }

    /**
     * 登录接口
     */
    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public Object login(HttpServletRequest request, @RequestBody LoginRO ro) throws WxErrorException {
        WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(ro.getCode());
        log.info("登录返回:{}", session.toString());
        UserEntity userEntity = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("openid", session.getOpenid()));
        if (userEntity == null) {
            //插入用户
            userEntity = new UserEntity();
            userEntity.setCreateTime(new Date());
            userEntity.setOpenid(session.getOpenid());
            userEntity.setUnionid(session.getUnionid());
            userEntity.setMaxScore(0L);
            userMapper.insert(userEntity);
            //自己是自己的好友
            FriendEntity friendEntity = new FriendEntity();
            friendEntity.setUserId(userEntity.getId());
            friendEntity.setFriendUserId(userEntity.getId());
            friendMapper.insert(friendEntity);
        }
        String ip = IpUtils.getIpAddress(request);
        //插入pv
        PVEntity pvEntity = new PVEntity();
        pvEntity.setCreateTime(new Date());
        pvEntity.setIp(ip);
        pvEntity.setOpenid(session.getOpenid());
        pvEntity.setUnionid(session.getUnionid());
        pvEntity.setUserId(userEntity.getId());
        pvMapper.insert(pvEntity);

        String currentDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        Integer count = uvMapper.selectCount(new QueryWrapper<UVEntity>()
                .eq("ip", ip)
                .eq("user_id", userEntity.getId())
                .between("create_time", currentDate + " 00:00:00", currentDate + " 23:59:59"));

        if (count == null || count == 0) {
            //插入uv
            UVEntity uvEntity = new UVEntity();
            uvEntity.setCreateTime(new Date());
            uvEntity.setIp(ip);
            uvEntity.setOpenid(session.getOpenid());
            uvEntity.setUnionid(session.getUnionid());
            uvEntity.setUserId(userEntity.getId());
            uvMapper.insert(uvEntity);
        }
        //返回信息
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        UserInfo userInfo = new UserInfo();
        userInfo.setSessionKey(session.getSessionKey());
        userInfo.setOpenid(session.getOpenid());
        userInfo.setUnionId(session.getUnionid());
        userInfo.setUserId(userEntity.getId());
        CacheUtils.putUserInfo(token, userInfo);

        LoginVO vo = new LoginVO();
        if (StringUtils.isNotEmpty(userEntity.getNickName()) && StringUtils.isNotEmpty(userEntity.getHeadImg())) {
            vo.setFirst(false);
        } else {
            vo.setFirst(true);
        }
        vo.setOpenid(session.getOpenid());
        vo.setUnionid(session.getUnionid());
        vo.setToken(token);
        vo.setUserId(String.valueOf(userEntity.getId()));
        return success(vo);
    }


    /**
     * 上传好友
     */
    @ApiOperation(value = "上传好友")
    @PostMapping("/upload/friend")
    public Object uploadFriend(@RequestHeader String token, @RequestBody UploadFriendRO ro) {
        if (StringUtils.isNotEmpty(ro.getUserId())) {
            UserEntity userEntity = userMapper.selectById(ro.getUserId());
            if (userEntity == null) {
                throw new RuntimeException("用户不存在！");
            }
            if (!ro.getUserId().equals(String.valueOf(CacheUtils.getUserId(token)))) {
                List<FriendEntity> friendEntities = friendMapper.selectList(new QueryWrapper<FriendEntity>()
                        .eq("user_id", ro.getUserId())
                        .eq("friend_user_id", CacheUtils.getUserId(token)));
                if (CollectionUtils.isEmpty(friendEntities)) {
                    //插入好友信息
                    FriendEntity friendEntity = new FriendEntity();
                    friendEntity.setUserId(Long.valueOf(ro.getUserId()));
                    friendEntity.setFriendUserId(CacheUtils.getUserId(token));
                    friendMapper.insert(friendEntity);
                }
                List<FriendEntity> friendEntitie2 = friendMapper.selectList(new QueryWrapper<FriendEntity>()
                        .eq("friend_user_id", ro.getUserId())
                        .eq("user_id", CacheUtils.getUserId(token)));
                if (CollectionUtils.isEmpty(friendEntities)) {
                    //插入好友信息
                    FriendEntity friendEntity = new FriendEntity();
                    friendEntity.setUserId(CacheUtils.getUserId(token));
                    friendEntity.setFriendUserId(Long.valueOf(ro.getUserId()));
                    friendMapper.insert(friendEntity);
                }
            }

        }

        return success();
    }

    /**
     * 上传用户信息
     */
    @ApiOperation(value = "上传用户信息")
    @PostMapping("/upload/userInfo")
    public Object uploadUserInfo(@RequestHeader String token, @RequestBody UploadUserInfoRO ro) {
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(CacheUtils.getSessionKey(token),
                ro.getEncryptedData(), ro.getIv());
        UserEntity userEntity = new UserEntity();
        userEntity.setId(CacheUtils.getUserId(token));
        userEntity.setNickName(userInfo.getNickName());
        userEntity.setHeadImg(userInfo.getAvatarUrl());
        userMapper.updateById(userEntity);
        return success();
    }

}
